package com.lihaogn.sell.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lihaogn.sell.dto.OrderDetailDto;
import com.lihaogn.sell.entity.Food;
import com.lihaogn.sell.entity.Order;
import com.lihaogn.sell.entity.OrderDetail;
import com.lihaogn.sell.mapper.FoodMapper;
import com.lihaogn.sell.mapper.OrderMapper;
import com.lihaogn.sell.service.OrderService;
import com.lihaogn.sell.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: OrderServiceImpl
 * @Description: TODO
 * @Author: lihao
 * @Date: 2019-05-17 14:12
 * @Version: 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private FoodMapper foodMapper;

    // === 查询 ===

    @Override
    public ListVo getOrderByCondition(SearchPageVo searchPageVo) {
        Map<String, Object> queryMap = new HashMap<>();
        ListVo listVo = new ListVo();

        List<OrderVo> orderList;
        int searchCount;

        Integer limit = searchPageVo.getLimit();
        Integer page = (searchPageVo.getPage() - 1) * limit;
        String name = searchPageVo.getName();
        String start = searchPageVo.getStart();
        String end = searchPageVo.getEnd();


        queryMap.put("page", page);
        queryMap.put("size", limit);

        queryMap.put("start", start);
        queryMap.put("end", end);
        queryMap.put("orderPayStatus", searchPageVo.getSelectValue());
        queryMap.put("name", name);

        List<OrderVo> orderVoList = orderMapper.queryOrderByCondition(queryMap);


        listVo.setCode(0);
        listVo.setMsg("success");
        listVo.setCount(orderVoList.size());
        listVo.setData(orderVoList);

        return listVo;
    }

    @Override
    public List<OrderDetailVo> getOrderDetailById(String orderId) {
        return orderMapper.queryOrderDetailById(orderId);
    }

    @Override
    public List<OrderVo> getAllOrder(String page, String limit) {
        Map<String, Integer> pageMap = new HashMap<>();

        int pageOne = Integer.valueOf(page);
        int pageSize = Integer.valueOf(limit);
        int start = (pageOne - 1) * pageSize;

        pageMap.put("page", start);
        pageMap.put("size", pageSize);

        return orderMapper.queryAllOrder(pageMap);
    }

    @Override
    public int getAllRowCount() {
        return orderMapper.queryAllRowCount();
    }

    // === 插入 ===

    @Override
    public int addOneOrder(Order order) {
        return orderMapper.insertOneOrder(order);
    }

    @Override
    public int addOneOrderDetail(OrderDetail orderDetail) {

        try {
            // 更新菜品销量与评分

            // 获取菜品信息
            Food food = foodMapper.queryOneFoodById(orderDetail.getFoodId());
            // 更新菜品销量
            int count = food.getFoodSaleCount();
            int newCount = count + orderDetail.getOrderItemCount();
            food.setFoodSaleCount(newCount);
            // 更新数据库
            foodMapper.updateOneFoodById(food);
            // 新增订单详情信息
            orderMapper.insertOneOrderDetail(orderDetail);

        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

        return 1;
    }

    // === 修改 ===

    @Override
    public int changeOrderPayStatus(String orderId) {
        return orderMapper.updateOrderPayStatus(orderId);
    }

    @Override
    public int changeOrder(String orderId, Double orderCost) {
        HashMap<String, Object> orderMap = new HashMap<>();
        orderMap.put("orderCost", orderCost);
        orderMap.put("orderId", orderId);

        return orderMapper.updateOrder(orderMap);
    }

    @Override
    public int updataOrderItemScore(Map<String, Object> reviewMap) {
        int i = 0;

        try {
            // 更新订单中菜品评分
            i = orderMapper.updataOrderItemScore(reviewMap);
            // 查询订单详细中菜品信息
            List<OrderDetailDto> orderDetailList = orderMapper.queryOrderDetailByFid((String) reviewMap.get("foodId"));
            // 计算平均评分
            int sum = 0;
            int count = 0;
            for (OrderDetailDto dto : orderDetailList) {
                count += dto.getOrderItemCount();
                sum += dto.getOrderItemCount() * dto.getOrderItemScore();
            }
            double avgScore = (double) Math.round((double) sum / count * 100) / 100;
            System.out.println("平均分：" + avgScore);
            // 更新菜品评分
            Food food = new Food();
            food.setFoodId((String) reviewMap.get("foodId"));
            food.setFoodScore(avgScore);
            // 更新数据库
            foodMapper.updateOneFoodById(food);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return i;
    }


    // === 删除 ===

    @Override
    public int deleteOneOrder(String orderId) {
        // 删除order对应的detail
        try {
            orderMapper.deleteOrderDetailByOrderId(orderId);
            orderMapper.deleteOneOrder(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int deleteMultiOrder(HttpServletRequest request) {
        // 记录删除的个数
        int num;
        BufferedReader reader;

        try {
            reader = request.getReader();

            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            ArrayList<String> idList = objectMapper.readValue(res.toString(), ArrayList.class);

            HashMap<String, Object> map = new HashMap<>();
            map.put("idList", idList);

            orderMapper.deleteMultiOrderDetail(map);
            num = orderMapper.deleteMultiOrder(map);
            if (num == idList.size()) {
                return 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
